import { computed, onMounted, ref, watch } from "vue";
import { MessageUtil } from "@/utils/messageUtil";
import { ResultData } from "@/api/types";
import { cloneDeep } from "lodash-es";

interface FileInfo {
  name: string;
  url: string;
  status: string;
}

export function useUploadHook(props: any, emits: any) {
  const fileList = ref([]);

  const changeValue = ref(props.value || []);

  const initFileList = () => {
    if (!props.value || !props.value.length) {
      fileList.value = [];
      return;
    }
    fileList.value = props.value!.map((item: any) => {
      return {
        name: item.name,
        url: item.url,
        status: "success"
      };
    });
  };

  watch(
    () => props.value,
    () => {
      initFileList();
      if (!isListEqual(props.value, changeValue.value)) {
        changeValue.value = props.value ? cloneDeep(props.value) : [];
      }
    },
    {
      deep: true
    }
  );

  // 对比两个文件列表是否相等
  const isListEqual = (fileList1: FileInfo[], fileList2: FileInfo[]) => {
    if (!fileList1 && !fileList2) {
      return false;
    }
    if (fileList1?.length !== fileList2?.length) {
      return false;
    }
    return JSON.stringify(fileList1) === JSON.stringify(fileList2);
  };

  onMounted(() => {
    initFileList();
  });

  watch(
    () => changeValue.value,
    value => {
      emits("update:value", value);
    },
    {
      deep: true
    }
  );

  const uploadSuccess = (response: ResultData, file: File, fileList: FileInfo[]) => {
    if (response.code && response.code === 500) {
      MessageUtil.error(response.msg);
    }
    changeValue.value.push({
      name: file.name,
      url: response.data
    });
  };

  const handleRemove = (file: FileInfo) => {
    let index = changeValue.value.findIndex((item: FileInfo) => item.url === file.url);
    changeValue.value.splice(index, 1);
  };
  const handleProgress = (event: any, file: any, fileList: any) => {};
  const handleError = (err: any, file: any, fileList: any) => {
    console.log(err);
    MessageUtil.error(err);
  };
  const handleExceed = () => {
    MessageUtil.error(`最多上传${props.item.limit}个文件`);
  };
  const beforeUpload = (file: File) => {
    console.log(file);
    let sizeUnitNum = 1;
    // 文件大小判断
    switch (props.item.config.sizeUnit) {
      case "KB":
        sizeUnitNum = 1024;
        break;
      case "MB":
        sizeUnitNum = 1024 * 1024;
        break;
      case "GB":
        sizeUnitNum = 1024 * 1024 * 1024;
        break;
    }
    let totalSize = props.item.config.fileSize * sizeUnitNum;
    if (file.size > totalSize) {
      if (props.item.typeId == "IMAGE_UPLOAD") {
        MessageUtil.error(`上传图片大小不能超过${props.item.config.fileSize}${props.item.config.sizeUnit}`);
      } else {
        MessageUtil.error(`上传文件大小不能超过${props.item.config.fileSize}${props.item.config.sizeUnit}`);
      }
      return false;
    }
    let isAccept = true;

    const fileIndex = file.name.lastIndexOf(".");
    const fileType = file.name.toLowerCase().substring(fileIndex);
    // 判断是否是数组
    if (props.item.accept && Array.isArray(props.item.accept)) {
      for (let ac of props.item.accept) {
        if (ac.indexOf("*") > -1) {
          isAccept = new RegExp(ac).test(fileType) || new RegExp(ac).test(file.type);
        } else {
          let rules = ac.split(",");
          for (let item of rules) {
            isAccept = false;
            if (item === fileType) {
              isAccept = true;
              break;
            }
          }
        }
        if (isAccept) {
          break;
        }
      }
    }
    if (!isAccept) {
      MessageUtil.error(`应该选择${props.item.accept}类型的文件`);
      return false;
    }
    return true;
  };

  const getUploadData = computed(() => {
    if (props.item.customAccept) {
      return {
        formItemId: props.item.vModel
      };
    } else {
      return {};
    }
  });

  return {
    fileList,
    uploadSuccess,
    handleRemove,
    handleProgress,
    handleError,
    handleExceed,
    beforeUpload,
    changeValue,
    getUploadData,
    initFileList
  };
}
